package com.allen.admin.service.server.manager.impl;

import com.allen.admin.service.common.domain.AdminUserOperLog;
import com.xxx.dao.GenericDao;
import com.xxx.page.DataPage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;

@Repository
public class AdminUserOperLogManager {
	
	@Autowired
    private GenericDao dao;
	
	public AdminUserOperLog insert(AdminUserOperLog obj) {
		assert obj != null;
		
		obj.setLogTime(LocalDateTime.now());
		int affected = dao.insertAndReturnAffectedCount("AdminUserOperLogMapper.insert", obj);
		if (affected > 0) {
			return obj;
		} else {
			return null;
		}
	}

	public AdminUserOperLog selectById(Long id) {
		assert id != null;
		
		AdminUserOperLog obj = dao.queryUnique("AdminUserOperLogMapper.selectById", id);
		return obj;
	}
	
	public DataPage<AdminUserOperLog> queryPage(
			DataPage<AdminUserOperLog> dataPage, 
			AdminUserOperLog qObj,
			LocalDate beginDate,
			LocalDate endDate) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("order", dataPage.getOrder());
		map.put("orderBy", dataPage.getOrderBy());
		
		if (qObj.getType() != null) {
			map.put("type", qObj.getType());
		}
		if (StringUtils.isNotBlank(qObj.getAction())) {
			map.put("action", "%" + qObj.getAction() + "%");
		}
		if (StringUtils.isNotBlank(qObj.getUser())) {
			map.put("user", "%" + qObj.getUser() + "%");
		}
		
		if (beginDate != null) {
			LocalDateTime beginTime = LocalDateTime.of(beginDate, LocalTime.of(0, 0, 0, 0));
			map.put("beginTime", beginTime);
		}
		if (endDate != null) {
			LocalDateTime endTime = LocalDateTime.of(endDate, LocalTime.of(0, 0, 0, 0));
			endTime = endTime.plusDays(1).minusNanos(1);
			map.put("endTime", endTime);
		}
		
		dataPage = dao.queryPage(
				"AdminUserOperLogMapper.countPage", 
				"AdminUserOperLogMapper.queryPage", map, dataPage);
		
		return dataPage;
	}

}
